package cn.edu.swu.database;

import cn.edu.swu.book.BOOK;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DBTool {

    //创建数据库
    private static BasicDataSource dataSource;

    static {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            dataSource=new BasicDataSource();
            dataSource.setUrl("jdbc:mysql://localhost:3306/bookstore");
            dataSource.setUsername("root");
            dataSource.setPassword("mysql123");
            dataSource.setMinIdle(5);
            dataSource.setMaxIdle(7);
            dataSource.setMaxTotal(20);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //protected构造函数保证外界无法创建实例 供子类使用
    protected DBTool(){}

    public Connection getDBConnection() throws SQLException {
        return dataSource.getConnection();
    }



    protected Boolean execute(String cudSQL) throws SQLException {
        try(Connection connection=dataSource.getConnection()){
            try(Statement statement=connection.createStatement()){
                System.out.println(cudSQL);
                return statement.execute(cudSQL);
            }
        }
    }

    //把查询的接口传进来
    protected void query(String sql, resultsetVisitor visitor) throws SQLException {
        System.out.println(sql);
        try(Connection connection=dataSource.getConnection()){
            try(Statement statement= connection.createStatement()){
                try(ResultSet resultSet= statement.executeQuery(sql)){
                    while(resultSet.next()){
                        visitor.visit(resultSet);
                    }
                }
            }
        }
    }



    //    public Connection getDbConnection() throws ClassNotFoundException, SQLException {
//        String dbUrl="jdbc:mysql://localhost:3306/bookstore";
//        String dbUser="root";
//        String dbPsw="mysql123";
//        Class.forName("com.mysql.cj.jdbc.Driver");
//        try{
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            Connection connection;
//            connection = DriverManager.getConnection(dbUrl,dbUser,dbPsw);
//            return connection;
//        } catch (ClassNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//    }
}
